package com.xander.utils;

import com.alibaba.fastjson.JSONObject;
import com.xander.entity.Cookie;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

/**
 * Created by YE on 2018/5/3.
 */
public class CookieUtils {

    //将cookie字符串转成cookie类
    public static Cookie formatCookie(String cookie) {
        String decookie = null;
        String sns = null;
        String trackid=null;
        Cookie co;
        try {
            try {
                decookie = URLDecoder.decode(cookie, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            String[] s = decookie.split(";");

            //获取snsInfo
            for (String str : s) {
                if (str.length() >= 8&&str.substring(1, 8).equals("snsInfo")) {
                    sns = str;
                }
                if (str.length() >= 9&&str.substring(1, 9).equals("track_id")) {
                    trackid = str.split("=")[1];
                    trackid=trackid.split("\"")[0];
                    break;
                }
            }
            String snsinfo = sns.split("=")[1];
            //将snsInfo分解到cookie类
            JSONObject jsonObject=JSONObject.parseObject(snsinfo);
            co = new Cookie();
            co.setElemeKey(jsonObject.get("eleme_key").toString());
            co.setNickname(jsonObject.get("nickname").toString());
            co.setOpenid(jsonObject.get("openid").toString());
            co.setName(jsonObject.get("name").toString());
            co.setAvatar(jsonObject.get("avatar").toString());
            co.setTrackId(trackid);
            co.setCookietext(cookie);
            co.setCount(5);
        } catch (Exception e) {
            co = null;
        }
        return co;
    }

}
